#!/bin/zsh

macos_instal_config="/usr/local/etc/com.filewave.macos_instal_config.plist"
server_dns=$(defaults read /usr/local/etc/fwcld.plist server)

# Pull current flag value from server
macos_instal_flag=$(curl -s -k -X GET -H "Authorization: $api_key"  https://${server_dns}/filewave/api/devices/internal/devices/${device_id}/details/custom_fields/fields -H "Content-Type: application/json" | tr "[" "\n" | awk -F "\"" '/\"name\":\"macos_instal_flag\"/ {print $(NF-1)}')

function echo_me {
        datef=$(date "+%Y-%m-%d %H:%M:%S.***")
        echo "$datef|main|CUSTOM|CLIENT|startosinstall_requirements $1" | tee -a /usr/local/etc/macos_instal.log
}

# Write to local plist for activation script to save it having to run another api query
case $macos_instal_flag in

	"INSTAL"|"ERASE")
		echo_me "Flag value: $macos_instal_flag"
		defaults write "$macos_instal_config" Status $macos_instal_flag
	;;
	*)
		echo_me "Exiting.  Flag set as: $macos_instal_flag"
		exit 210
	;;
esac


function exit_fail {

	# - 210: This exit code will cause the Fileset to be treated like the
	#        installation was successful (unless another requirements script fails,)
	#        but the Fileset will not be downloaded nor installed.
	echo_me "Requirements not met: FAILED"

	defaults write "$macos_instal_config" Status FAILED

	curl -s -k -X PATCH -H "Authorization: $api_key"  "https://${server_dns}/api/devices/v1/devices/${device_id}" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{  \"custom_fields\": {\"macos_instal_flag\": \"FAILED\"}}" &>/dev/null

	echo_me "$1"
	exit 210
}

# Minimum space required 26GB for 10.12+, otherwise 44GB
# Added 12GB for size of installer

os_vers=$(sw_vers -productVersion)

min_space=38

if [ ${os_vers%%.*} -eq 10 ]
then
        if [ ${os_vers##*.} -lt 12 ]
        then
                min_space=56
        fi
fi

free_space=$(df -g / | awk '/\// {print $4}')

if [ $free_space -lt $min_space ]
then
	exit_fail "Not enough free space.  Threshold: $min_space, Available: ${free_space}GB"
fi

# Command differs between Apple M1 and Intel
cpu_brand=$(sysctl machdep.cpu.brand_string | awk -F ":" '{print $NF}')
echo_me $cpu_brand

# Ensure Apple M1 conditions are met
if [[ "$cpu_brand" =~ "Apple M1" ]]
then
	dseditgroup -o checkmember -m $local_admin admin &>/dev/null

	if [ $? -ne 0 ]
	then
		exit_fail "User $local_admin is not an admin"
	else
		secure_token_enabled=$(sysadminctl -secureTokenStatus $local_admin 2>&1)
		if [[ ! "$secure_token_enabled" =~ "ENABLED" ]]
		then
			echo_me "$secure_token_enabled"
			exit_fail "Admin user $local_admin does not have a secure token"
		fi
	fi
fi

exit 0